package com.cruise.game.security.handler;

import com.alibaba.fastjson2.JSON;
import com.cruise.game.common.api.ApiCode;
import com.cruise.game.common.api.ApiResult;
import com.cruise.game.common.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义访问拒绝处理器
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        log.error("访问拒绝，没有权限: {}", e.getMessage());
        
        response.setContentType(CommonConstants.CONTENT_TYPE_JSON);
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.getWriter().write(JSON.toJSONString(ApiResult.fail(ApiCode.FORBIDDEN, "没有操作权限")));
    }
}
